# encoding: utf-8
"""
此模块为tree主程序，但仅为一张空皮，
通过链接tools里的工具，接受命令行指令配对相应的工具并传参，是Tree负责与外界交互的控制中枢
"""
import sys
from os.path import dirname, join

from Error.Error import send_error
from Tools.dis import Dis
from Tools.clean import count_remove
from Tools.tshell import tshell
from Tools.build import build
from Tools.run import run
from Tools.brun import brun
from Tools.crun import crun
from Tools.grammar import Grammar
from Tools.token import Token
from Tools.all import count_build
from Tools.all import count_build
from Tools.call import run_all
from Tools.update import update
from Tools.buildsetup import buildinstall
from Tools.uninstall import uninstall
from Tools.byte_code import byte_code
from Tools.tdb import tdb


def __help(path: str = join(dirname(__file__), "./Doc/cmd_instruction.txt")) -> None:
    """指令操作提示"""
    print("Tree是Tree语言的虚拟机和编译器", end="\n\n")
    with open(path, encoding="UTF-8") as file:
        index = 0
        for i in file:
            if index % 2 == 0:
                print(i, end="\n")
            index += 1


def re(funcname):
    """
    匹配合适的函数和标签
    """
    try:
        return d[funcname], "common"
    except KeyError:
        return other_d[funcname], "other"


def check(pattern):
    """
    检查模式是否存在
    """
    if not (pattern in d or pattern in other_d):
        # 没有则给出提示
        print(f"{pattern} is no here.")
        print("Help:")
        __tip()
        sys.exit()


def init(argv):
    return argv[2:], argv[1]


def main():
    argv = sys.argv
    if len(argv) == 1:
        # 只有主程序入口, 启动交互模式
        tshell()
    else:
        # 标准流程

        # 文件列表, 模式/对应函数
        compile_list, pattern = init(argv)
        check(pattern)
        func, func_type = re(pattern)

        if len(compile_list) >= 1:
            if func_type == "common":
                for f in compile_list:
                    func(f)
            elif func_type == "other":
                func(compile_list)
        else:
            # 可能不需要参数
            try:
                func()
            except TypeError:
                send_error("ArgumentError", pattern)


# 模式对应的函数,通过指令取值时选择对应函数，参数一个个按顺序传递
d = {
    "run": run,
    "build": build,
    "dis": Dis,
    "token": Token,
    "grammar": Grammar,
    "brun": brun,
    "crun": crun,
    "clean": count_remove,
    "tshell": tshell,
    "all": count_build,
    "call": run_all,
    "update": update,
    "uninstall": uninstall,
    "byte_code": byte_code,
    "help": __help,
    "tdb": tdb,
}

# 模式对应的特殊函数,通过指令取值时选择对应函数，参数一次性传递
other_d = {
    "buildsetup": buildinstall,
}

if __name__ == "__main__":
    main()
